//
//  TLSearchListViewController.m
//  WXReader
//
//  Created by huaya on 2025/4/1.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLSearchListViewController.h"
#import "TL_SearchBar.h"
#import "HXTagsCell.h"
#import "HXTagAttribute.h"
#import "TLSearchResultViewController.h"

@interface TLSearchListViewController ()<DPSearchBarDelegate,UITableViewDelegate,UITableViewDataSource>;
@property (nonatomic, strong) TL_BasicNavBarView *navigationBar;
@property (nonatomic, strong) TL_SearchBar *searchView;

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray<NSString *> *historyArray;

@property (nonatomic, strong) HXTagCollectionViewFlowLayout *tagViewLayout;//布局layout
@property (nonatomic, strong) HXTagAttribute *tagViewAttr;

@property (nonatomic, assign) BOOL editing;
@property (nonatomic, assign) NSInteger showType;

@property (nonatomic, strong) TLSearchResultViewController *resultVC;

@end

@implementation TLSearchListViewController

- (TLSearchResultViewController *)resultVC{
    if (!_resultVC) {
        _resultVC = [[TLSearchResultViewController alloc] init];
    }
    return _resultVC;
}
- (UITableView *)tableView{
    if (!_tableView) {
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MK_SCREEN_SAVE_BOTTOM_HEIGHT)];
        footView.backgroundColor = UIColor.clearColor;
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.tableFooterView = footView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 15.0, *)) {
            self.tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}

- (TL_BasicNavBarView *)navigationBar
{
    if (!_navigationBar) {
        _navigationBar = [[TL_BasicNavBarView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, PUB_NAVBAR_HEIGHT)];
        _navigationBar.navCurrentController = self;
        _navigationBar.backgroundColor = kWhiteColor;
        _navigationBar.userInteractionEnabled = YES;
        [_navigationBar hiddenLeftBarButton];
        [_navigationBar setSmallSeparator];
    }
    return _navigationBar;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.navigationBar];
    
    TL_SearchBar *searchView = [[TL_SearchBar alloc] init];
    searchView.searchTextField.userInteractionEnabled = YES;
//    [searchView setHiddenCancelButton];
    searchView.searchTextField.backgroundColor = kGrayViewColor;
    searchView.layer.cornerRadius = 16.5;
    searchView.layer.masksToBounds = YES;
    searchView.placeholderText = WXLocalizedString(@"搜索书籍/作者");
    searchView.backgroundColor = [UIColor clearColor];
    searchView.delegate = self;
    [self.navigationBar addSubview:searchView];
    _searchView = searchView;
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.navigationBar).offset(kMoreHalfMargin);
        make.right.equalTo(self.navigationBar).offset(-kMoreHalfMargin);
        make.centerY.equalTo(self.navigationBar.defaultLeftButton);
        make.height.mas_equalTo(35.0);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBar.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    [self addChildViewController:self.resultVC];
    [self.view addSubview:self.resultVC.view];
    [self.resultVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navigationBar.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    self.resultVC.view.hidden = YES;
    
    [self loadDataSource];
}

- (void)cancelButtonClicked{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchButtonClickedWithSearchText:(NSString *)text{
    if (!text || text.length == 0) {
//        return;
    }
    if (text.length > 50){
        text = [text substringToIndex:50];
    }
    [self saveSearchText:text];
    self.searchView.searchText = text;
    [self networkWithKeyWord:text];
}
- (void)networkWithKeyWord:(NSString *)keyWord{
    self.resultVC.view.hidden = NO;
    [self.resultVC searchWithText:keyWord];
}

- (void)loadDataSource{
    //搜索历史
    if ([TL_UtilsHelper getSearchHistory].count > 0) {
        self.historyArray = [TL_UtilsHelper getSearchHistory].mutableCopy;
    }else{
        self.historyArray = @[].mutableCopy;
    }
    
    [self.tableView reloadData];
}

/** 保存搜索记录 */
- (void)saveSearchText:(NSString *)text{
    if (!text || text.length == 0) {
        return;
    }
    for (NSString *str in self.historyArray) {
        if ([str isEqualToString:text]) {
            [self.historyArray removeObject:str];
            break;
        }
    }
    [self.historyArray insertObject:text atIndex:0];
    [TL_UtilsHelper saveSearchHistory:self.historyArray.copy];
}

//清理历史记录
- (void)btnCleanAction{
    self.editing = YES;
    [self.tableView reloadData];
}
//删除全部
- (void)btnCleanAllAction{
    
    TL_AlertView *alert = [[TL_AlertView alloc] init];
    alert.alertViewDetailContent = WXLocalizedString(@"确定清空搜索历史？");
    alert.alertViewCancelTitle = WXLocalizedString(@"取消");
    alert.alertViewConfirmTitle = WXLocalizedString(@"确定");
    alert.confirmButtonClickBlock = ^{
        if (self.historyArray) {
            [self.historyArray removeAllObjects];
            [TL_UtilsHelper saveSearchHistory:self.historyArray.copy];
        }
        [self.tableView reloadData];
    };
    alert.cancelButtonClickBlock = ^{
        
    };
    [alert showAlertView];
}

#pragma mark - ***** UITableView delegate ******
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *cellId = @"searchCell";
    HXTagsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[HXTagsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.contentView.backgroundColor = [UIColor whiteColor];
    }
    self.tagViewAttr.haveCloseBtn = self.editing;
    cell.tagAttribute = self.tagViewAttr;
    
    cell.layout = self.tagViewLayout;
    cell.tags = self.historyArray.copy;
    [cell reloadData];
    MJWeakSelf
    cell.completion = ^(NSArray *selectTags, NSInteger currentIndex) {
        
        weakSelf.searchView.searchText = self.historyArray[currentIndex];
        
        [weakSelf networkWithKeyWord:self.historyArray[currentIndex]];
        
    };
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 36)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(16, 10, 150, 20)];
    lab.textColor = [UIColor colorWithHexString:@"#333333"];
    lab.font = MK_FONT_PFSC_Medium(16);
    lab.text = @"Search History";
    lab.center = CGPointMake(lab.center.x, view.center.y);
    [view addSubview:lab];

    UIButton *btnAll = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnAll setImage:[UIImage imageNamed:@"com_icon_delete_0"] forState:UIControlStateNormal];
    [btnAll setTitle:@" Clear" forState:UIControlStateNormal];
    [btnAll setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
    btnAll.titleLabel.font = SYSTEM_FONT(12);
    btnAll.frame = CGRectMake(kScreenWidth-70, 10, 60, 36);
    [btnAll addTarget:self action:@selector(btnCleanAllAction) forControlEvents:UIControlEventTouchUpInside];
    btnAll.center = CGPointMake(btnAll.center.x, view.center.y);
    [view addSubview:btnAll];
    
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 36;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 90;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (HXTagCollectionViewFlowLayout *)tagViewLayout{
    if (!_tagViewLayout) {
        _tagViewLayout = [HXTagCollectionViewFlowLayout new];
        _tagViewLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _tagViewLayout.itemSize = CGSizeMake(100.0f, 26.0f);
        _tagViewLayout.minimumInteritemSpacing = 8.f;
        _tagViewLayout.minimumLineSpacing = 12.0f;
        _tagViewLayout.sectionInset = UIEdgeInsetsMake(0.0f, 15.0f, 0.0f, 15.0f);
    }
    return _tagViewLayout;
}

- (HXTagAttribute *)tagViewAttr{
    if (!_tagViewAttr) {
        _tagViewAttr = [[HXTagAttribute alloc] init];
        _tagViewAttr.titleSize = 14.0;
        _tagViewAttr.textColor = [UIColor colorWithHexString:@"#333333"];
        _tagViewAttr.normalBackgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
        _tagViewAttr.cornerRadius = 8.f;
        _tagViewAttr.tagSpace = 12.f;
        _tagViewAttr.selectedBackgroundColor = [UIColor colorWithHexString:@"#F2F2F2"];
        _tagViewAttr.closeBtnWidth = 10;
    }
    return _tagViewAttr;
}


@end
